/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.baseDataView;

/**
 * 说明：
 * 员工管理
 * @Author：黄盛强
 * @Date：2012-03-20
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.TreePath;

import com.ruipengkj.bean.TDept;
import com.ruipengkj.bean.TEmployee;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundGray;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.jpanel.QueryPanel;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.component.jtree.OverwriteDefaultMutableTreeNode;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.DataEmployeesModel;
import com.ruipengkj.service.TDeptService;
import com.ruipengkj.service.TEmployeeService;
import com.ruipengkj.view.base.BasePagePanel;

public class DataEmployeesPanel extends BasePagePanel<TEmployee> implements PageDelegale ,Runnable, MouseMotionListener{
	private static final long serialVersionUID = 1L;
	
	private JLabelJTextFieldComponent numberTF;//员工号Label
	private JLabelJTextFieldComponent nameTF;//名字
	private JButton queryButton;//查询按钮
	private JButton addButton; //增加员工
	private JButton updateButton; //修改员工
	private JButton delButton; //删除员工
	private JButton createCatalogButton;//添加员工部门
	
	private JButton queryDepartmentButton;//查询部门按钮
	
	private JLabelJTextFieldComponent queryDepartmentTF;//部门
	
	private DataEmployeesModel dataEmployeesModel;
	private PagingComponent pagingComponent;//翻页组件
	private PageView<TEmployee> pageView;//翻页主键
	private TEmployeeService tEmployeeService;//员工操作对象
	
	private JTable table = null;
	private JScrollPane tableJsp = null;
	private JScrollPane treeJsp = null;
	
	private JMenuItem addProductCatalogButton, deleteProductCatalogButton,
	updateProductCatalogButton, refreshProductCatalogButton;// 添加、删除、修改分类按钮
	
	private JPopupMenu treePopupMenu;
	
	private DataDepartmentAddDialog dataDepartmentAddDialog;//添加部门界面
	private DataEmployeesAddOrModifyDialog dataEmployeesAddDialog;//添加员工界面
	private DataTDeptTreePanel dataTDeptTreePanel;//左边树
	
	private TDeptService tDeptService;//部门
	
	private TDept tDept;//部门
	
	public DataEmployeesPanel() {
		setLayout(new BorderLayout());
		this.setBackground(Util.PANEL_COLOR);
		this.init();
		this.initListener();
		tEmployeeService=BuildSpringApplication.getInstance().getTEmployeeServiceImpl();
		tDeptService = BuildSpringApplication.getInstance().getTDeptServiceImpl();
		this.treeMousePopMenu();// 树 鼠标右键
	}
	
	private JPanel initLeft() {
		dataTDeptTreePanel=new DataTDeptTreePanel();
		treeJsp=uiFactory.createJScrollPane(dataTDeptTreePanel);
		
		JPanel jp2 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		queryDepartmentButton = new RPJButtonBlue("查询");
		queryDepartmentTF = new JLabelJTextFieldComponent("部门查询", 15);
		jp2.add(queryDepartmentTF);
		jp2.add(queryDepartmentButton);
		queryDepartmentButton.addMouseListener(this);
		
		JPanel jp3 =  uiFactory.createFlowJPanel(FlowLayout.LEFT);
		createCatalogButton=new RPJButtonRoundBlue("新建部门");
		jp3.add(createCatalogButton);
		
		JPanel left_panel =  uiFactory.createBorderJPanel();
		left_panel.add(jp3,BorderLayout.NORTH);
		left_panel.add(treeJsp, BorderLayout.CENTER);
		left_panel.add(jp2, BorderLayout.SOUTH);
		
		left_panel.setPreferredSize(new Dimension(250, 250));
		return left_panel;
	}
	
	private JPanel initRight() {
		JPanel right_panel =  uiFactory.createBorderJPanel();
		pageView = new PageView<TEmployee>();
		dataEmployeesModel = new DataEmployeesModel();
		table=uiFactory.createRPJTable(dataEmployeesModel, null, this, 30, JLabel.CENTER);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		
		TabelUtil.hideTableColumn(0, table);
		
		table.addKeyListener(this);
		tableJsp=uiFactory.createJScrollPane(table);
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
		
		JPanel gardPanel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_DOWN_BG_1).getImage());
		gardPanel.setLayout(new GridLayout(1,2));
		JPanel jp1= uiFactory.createFlowJPanel(FlowLayout.LEFT);
		addButton = new RPJButtonRoundBlue("添加(Ctrl+A)");
		updateButton = new RPJButtonRoundGray("修改Ctrl+M)");
		delButton = new RPJButtonRoundOrager("删除Ctrl+D)");
		jp1.add(addButton);
		jp1.add(updateButton);
		jp1.add(delButton);
		gardPanel.add(jp1);
		gardPanel.add(pagingComponent);
		right_panel.add(tableJsp,BorderLayout.CENTER);
		right_panel.add(gardPanel,BorderLayout.SOUTH);
		return right_panel;
	}
	
	private void init() {

		JSplitPane jsp = new JSplitPane();
		jsp.setOpaque(false);
		jsp.add(initLeft(), JSplitPane.LEFT, 0);
		jsp.add(initRight(), JSplitPane.RIGHT, 0);
		
		this.add(initTop(),BorderLayout.NORTH);
		this.add(jsp,BorderLayout.CENTER);
		//排序
		TableRowSorter<DataEmployeesModel> tableRowSorter = new TableRowSorter<DataEmployeesModel>(dataEmployeesModel);  
		table.setRowSorter(tableRowSorter);
	}
	
	private JPanel initTop() {
		QueryPanel queryPanel=new QueryPanel("员工管理",ImageFactory.loadImage(ImageFactory.FUN_3_ICON_2));
		JPanel top_panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		numberTF= new JLabelJTextFieldComponent("员工号：", 20);
		nameTF = new JLabelJTextFieldComponent("名称：", 20);
		queryButton = new RPJButtonBlue("查询");
		
		top_panel.add(numberTF);
		top_panel.add(nameTF);
		top_panel.add(queryButton);
		
		queryPanel.addPanel(top_panel);
//		queryPanel.addBoxPanel(top_panel);
		return queryPanel;
	}
	
	//初始化监听器
	private void initListener() {
		numberTF.getText().addKeyListener(this);
		nameTF.getText().addKeyListener(this);
		queryButton.addActionListener(this);
		addButton.addActionListener(this);
		addButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		updateButton.addActionListener(this);
		updateButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		delButton.addActionListener(this);
		delButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		queryDepartmentButton.addActionListener(this);
		createCatalogButton.addActionListener(this);
		dataTDeptTreePanel.getTree().addMouseListener(this);
		dataTDeptTreePanel.getTree().addMouseMotionListener(this);
	}
	
	
	@Override
	public void run() {
		this.termQuery(1);
	}
	
	//条件查询
	protected void termQuery(final int currentPage){
		final TEmployee temployee=new TEmployee();
		temployee.setEmployeeSn(numberTF.getText().getText().trim());
		temployee.setName(nameTF.getText().getText().trim());
		temployee.setTDept(tDept);
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
					pageView.setCurrentPage(currentPage);
					PageModel<TEmployee> pageModel = tEmployeeService.getScrollService(pageView.getFirstResult(), pageView.getMaxResult(),temployee);
					pageView.setPageModel(pageModel);
					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
					if(pageModel!=null){
						TabelUtil.clearTableRowSorter(table);
						dataEmployeesModel.setRowData(pageModel.getResultList());
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								TabelUtil.setJTabelAutoClumnWidth(table);
								pagingComponent.show();
							}
						});
					}else{
						//没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						dataEmployeesModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==queryButton){
			//查询按钮
			this.termQuery(1);
		}else if(e.getSource()==addButton){
			//添加按钮
			OverwriteDefaultMutableTreeNode selectedNode = (OverwriteDefaultMutableTreeNode) dataTDeptTreePanel.getTree()
					.getLastSelectedPathComponent();
			
			dataEmployeesAddDialog = new DataEmployeesAddOrModifyDialog(null,"添加员工",true);
			if (selectedNode!= null &&selectedNode.getNodeStringID() != null) {
				dataEmployeesAddDialog.showDialog(null, selectedNode.getNodeName());
			} else {
				dataEmployeesAddDialog.showDialog(null, null);
			}
			
			if(dataEmployeesAddDialog.isSuccess){
				this.termQuery(1);
			}
		}else if(e.getSource()==updateButton){
			//修改按钮
			this.modifyEmployee();
		}else if(e.getSource()==delButton){
			//删除按钮
			this.deleteEmployee();
		}else if(e.getSource()==addProductCatalogButton){
			//添加部门按钮
			dataDepartmentAddDialog = new DataDepartmentAddDialog(null,"添加部门",true);
			dataDepartmentAddDialog.showDialog(null);
			if(dataDepartmentAddDialog.isSuccess){
				OverwriteDefaultMutableTreeNode child = new OverwriteDefaultMutableTreeNode(dataDepartmentAddDialog.gettDept().getDeptID(), dataDepartmentAddDialog.gettDept().getName()
						, dataDepartmentAddDialog.gettDept().getDes());
    			OverwriteDefaultMutableTreeNode parent=(OverwriteDefaultMutableTreeNode) dataTDeptTreePanel.getTreeModel().getRoot();
    			if(parent!=null){
    				dataTDeptTreePanel.getTreeModel().insertNodeInto(child, parent, parent.getChildCount());
    			}
			}
		}else if(e.getSource()== updateProductCatalogButton){
			//修改部门按钮
			dataDepartmentAddDialog = new DataDepartmentAddDialog(
					null, "修改部门分类", true);
			OverwriteDefaultMutableTreeNode selectedNode = (OverwriteDefaultMutableTreeNode) dataTDeptTreePanel.getTree().getLastSelectedPathComponent();
			dataDepartmentAddDialog.showDialog(selectedNode.getNodeStringID());
			if (dataDepartmentAddDialog.isSuccess) {
				selectedNode.setNodeName(dataDepartmentAddDialog.getName());
				OverwriteDefaultMutableTreeNode newNode = new OverwriteDefaultMutableTreeNode(selectedNode.getNodeStringID(), dataDepartmentAddDialog.gettDept().getName()
						, dataDepartmentAddDialog.gettDept().getDes());
				selectedNode.setUserObject(newNode);
				dataTDeptTreePanel.getTree().updateUI();
			}
		}else if(e.getSource() == deleteProductCatalogButton) {
			//删除部门按钮
			delNode();
		}else if(e.getSource()==queryDepartmentButton){
			//查询部门按钮
				queryDept();
		} else if (e.getSource() == refreshProductCatalogButton) {
			//刷新商品分类
			dataTDeptTreePanel.refreshModel();
		}else if(e.getSource()==createCatalogButton){
			addProductCatalogButton.doClick();
		}
	}
	
	// 删除节点的方法
	protected void delNode() {
		OverwriteDefaultMutableTreeNode selectedNode = (OverwriteDefaultMutableTreeNode) dataTDeptTreePanel.getTree()
				.getLastSelectedPathComponent();
		if (selectedNode != null && selectedNode.getParent() != null) {
			// 判断选中的节点是否含有子节点
			if (Util.showConfirmDialog("确定删除此部门？（若部门存在员工，将清空部门员工所对应的部门）") != 0)
					return;
			TEmployee tEmployee = new TEmployee();//删除部门前，先把该部门的员工所属部门清空
			tEmployee.setTDept(new TDept(selectedNode.getNodeStringID()));
			try {
				List<TEmployee> tEmployeeList = tEmployeeService.findService(tEmployee);//查出该部门所有员工
				if (tEmployeeList != null) {
//					if (Util.showConfirmDialog("此部门存在员工，删除部门将清空部门员工所对应的部门。\n确定删除吗？") != 0)
//						return;
					for (int i = tEmployeeList.size() - 1; i >= 0; --i) {//清空员工部门
						tEmployeeList.get(i).setTDept(null);
						tEmployeeService.modifyService(tEmployeeList.get(i));
					}
					termQuery(1);
				}
				tDeptService.deleteService(selectedNode.getNodeStringID());
			} catch (Exception e) {
				e.printStackTrace();
			}
			dataTDeptTreePanel.getTreeModel().removeNodeFromParent(selectedNode);
		}
	}
	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getSource()==table){
			if(e.getKeyCode()==KeyEvent.VK_DELETE){
				//删除员工
				this.deleteEmployee();
			}
		}else if(e.getSource()==numberTF.getText()||e.getSource()==nameTF.getText()){
			//查询
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
				queryButton.doClick();
			}
		}
	}
	
	@Override
	public void mouseEntered(MouseEvent e) {
		
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getSource()==table){
			if(e.getClickCount() == 2){
				//修改员工
				this.modifyEmployee();
    		}
		}else if(e.getSource()==dataTDeptTreePanel.getTree()){
			if (e.getButton() == MouseEvent.BUTTON3) {
				// 鼠标右键
				if (e.getModifiers() == Event.META_MASK) {
					switch(dataTDeptTreePanel.getTree().getLeadSelectionRow()) {
						case -1:
						case 0:
							treePopupMenu.remove(deleteProductCatalogButton);
							treePopupMenu.remove(updateProductCatalogButton);
							break;
						default:
							treePopupMenu.add(deleteProductCatalogButton, 1);
							treePopupMenu.add(updateProductCatalogButton, 2);
					}
					treePopupMenu.show(dataTDeptTreePanel.getTree(), e.getX() + 10, e.getY() + 3);
					return;
				}
			}else{
				OverwriteDefaultMutableTreeNode treeNode=(OverwriteDefaultMutableTreeNode)dataTDeptTreePanel.getTree().getLastSelectedPathComponent(); 
				if(null!=treeNode&&treeNode.isLeaf()){
					tDept=new TDept(treeNode.getNodeStringID());
					this.termQuery(1);
				}else{
					tDept=null;
					this.termQuery(1);
				}
			}
		}
	}
	//删除员工
	private void deleteEmployee(){
		if(table.getRowCount()!=0){
			int[] rows=table.getSelectedRows();
			if(rows != null && rows.length != 0){
				String ok = "";
				if(Util.showConfirmDialog("是否要删除选择记录")==0){
					for (int i = 0,length = rows.length; i < length; ++i) {
						String employeeID=(String)table.getValueAt(rows[i], 0);
						if (employeeID.equals("aAAh1tkdgoqMItc")) {
							Util.showMessageDialog("此用户不能删除！");
							return;
						}
						try {
							tEmployeeService.deleteService(employeeID);
						} catch (Exception e1) {
							ok += "第"+(i+1)+"条数据删除失败！\n";
							e1.printStackTrace();
						}
					}
					this.termQuery(1);
					if (ok.equals("")) {
						JOptionPane.showMessageDialog(null, "删除成功");
					} else {
						JOptionPane.showMessageDialog(null, ok);
					}
				}
			}else{
				JOptionPane.showMessageDialog(null,"请选择行再进行删除");
				return;
			}
		}
	}
	
	//修改员工
	private void modifyEmployee(){
		if(table.getRowCount()!=0){
			int row=table.getSelectedRow();
			if(row!=-1){
				String empID=(String)table.getValueAt(row, 0);
				try {
					TEmployee employee=tEmployeeService.getByIdService(empID);
					dataEmployeesAddDialog = new DataEmployeesAddOrModifyDialog(null,"修改员工",true);
					dataEmployeesAddDialog.showDialog(employee, null);
					if(dataEmployeesAddDialog.isSuccess){
						this.termQuery(1);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}else{
				JOptionPane.showMessageDialog(null,"请选择行在进行修改");
				return;
			}
		}
	}
	
	@Override
	protected PageView<TEmployee> getPageView() {
		return pageView;
	}

	public JTable getTable() {
		return table;
	}
	
	// 树鼠标右键
	private void treeMousePopMenu() {
		treePopupMenu = new JPopupMenu();
		addProductCatalogButton = new JMenuItem("添加");
		deleteProductCatalogButton = new JMenuItem("删除");
		updateProductCatalogButton = new JMenuItem("修改");
		refreshProductCatalogButton = new JMenuItem("刷新");
		addProductCatalogButton.addActionListener(this);
		deleteProductCatalogButton.addActionListener(this);
		updateProductCatalogButton.addActionListener(this);
		refreshProductCatalogButton.addActionListener(this);
		treePopupMenu.add(addProductCatalogButton);
		treePopupMenu.add(deleteProductCatalogButton);
		treePopupMenu.add(updateProductCatalogButton);
		treePopupMenu.add(refreshProductCatalogButton);
	}

	private boolean queryNode(JTree tree, int j) {
		
		String keyWord = queryDepartmentTF.getText().getText().trim();
		for (int i = j >= 0 ? j+1 : 0; i < tree.getRowCount(); ++i) {
			OverwriteDefaultMutableTreeNode node = (OverwriteDefaultMutableTreeNode)tree.getPathForRow(i).getLastPathComponent();
			if (node.getNodeName().contains(keyWord)) {
				tree.setSelectionRow(i);
				return true;
			}
			tree.expandRow(i);
		}
		return false;
	}
//	@Override
	public void queryDept() {
		JTree tree = dataTDeptTreePanel.getTree();
		tree.expandRow(0);
		int j = 0;
		if(tree.getSelectionRows() == null||tree.getSelectionRows().length==0){
			j=-1;
		}else{
			j=tree.getSelectionRows()[0];
		}
		if (!queryNode(tree, j)) {
			if (j > 0) {
				if (Util.showConfirmDialog("无结果，是否从头搜索？") == 0) {
					if (!queryNode(tree, -1)) {
						JOptionPane.showMessageDialog(null, "无结果!");
					}
				}
			} else {
				JOptionPane.showMessageDialog(null, "无结果!");
			}
		}
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		
	}

	//鼠标移动时
	@Override
	public void mouseMoved(MouseEvent e) {
		JTree tree = dataTDeptTreePanel.getTree();
		TreePath treePath = tree.getPathForLocation(e.getX(), e.getY());
		if (treePath != null) {
			OverwriteDefaultMutableTreeNode treeNode = (OverwriteDefaultMutableTreeNode)treePath.getLastPathComponent();
			tree.setToolTipText(treeNode.getText() == "" ? null:treeNode.getText());
		} else {
			tree.setToolTipText(null);
		}
	}

	@Override
	public void clear() {
		dataEmployeesModel.clear();
		numberTF.getText().setText("");//员工号Label
		nameTF.getText().setText("");;//名字
	}
}